package com.cloud.ding_talk;

import com.cloud.ding_talk.vo.DingNotice;
import com.cloud.entity.AuthBody;
import com.cloud.entity.AuthUser;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 钉钉工具类
 *
 * @author yzj
 */
public class DingTalkUtils {

    private final Logger logger = LoggerFactory.getLogger(DingTalkUtils.class);

    private String appKey;

    private String appSecret;

    public DingTalkUtils(String appKey, String appSecret) {
        this.appKey = appKey;
        this.appSecret = appSecret;
    }

    /**
     * 获取企业内部应用的access_token
     **/
    private String getAccessToken() {
        String access_token = null;
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(appKey);
        request.setAppsecret(appSecret);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = null;
        try {
            response = client.execute(request);
            if (response.isSuccess()) {
                access_token = response.getAccessToken();
            }
        } catch (ApiException e) {
            logger.error("获取钉钉AccessToken失败:" + e);
        }
        return access_token;
    }

    /**
     * 获取企业人员详情
     **/
    public AuthUser getDingUserInfo(AuthBody authBody) {
        // 获取Access_token
        String access_token = getAccessToken();
        // 获取用户信息
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(authBody.getAuthCode());
        request.setHttpMethod("GET");
        try {
            OapiUserGetuserinfoResponse response = client.execute(request, access_token);
            if (response.isSuccess()) {
                // 根据 Userid获取用户信息
                return getDingUserInfoByUserId(response.getUserid(), access_token);
            }
        } catch (ApiException e) {
            logger.error("根据code获取钉钉人员失败:" + e);
        }
        return null;
    }

    /**
     * 根据 Userid钉钉用户信息
     **/
    public AuthUser getDingUserInfoByUserId(String userId, String accessToken) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
        OapiV2UserGetRequest request = new OapiV2UserGetRequest();
        request.setUserid(userId);
        request.setLanguage("zh_CN");
        try {
            AuthUser authUser = null;
            OapiV2UserGetResponse response = client.execute(request, accessToken);
            if (response.isSuccess()) {
                authUser = new AuthUser();
                authUser.setAccountId(userId);
                authUser.setAccount(response.getResult().getName());
                authUser.setLastName(response.getResult().getName());
                authUser.setGovEmpAvatar(response.getResult().getAvatar());
                authUser.setMobile(response.getResult().getMobile());
                authUser.setTelePhone(response.getResult().getTelephone());
                authUser.setEmail(response.getResult().getEmail());
                authUser.setOpenid(response.getResult().getUnionid());
            }
            return authUser;
        } catch (ApiException e) {
            return null;
        }
    }

    /**
     * 钉钉消息通知
     **/
    public void dingTalkMessageNotification(DingNotice notice) {
        try {
            String accessToken = getAccessToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(notice.getAgentId());
            request.setUseridList(notice.getAccountIds());
            request.setToAllUser(false);
            OapiMessageCorpconversationAsyncsendV2Request.Text reqText = new OapiMessageCorpconversationAsyncsendV2Request.Text();
            reqText.setContent(notice.getContent());
            OapiMessageCorpconversationAsyncsendV2Request.Msg message = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            message.setMsgtype("text");
            message.setText(reqText);
            request.setMsg(message);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);
            logger.info("钉钉发送消息:" + rsp.getBody());
        } catch (ApiException e) {
            logger.error("钉钉发送消息失败:" + e);
        }
    }

}
